import {
  Body,
  Controller,
  Delete,
  Get,
  NotFoundException,
  Patch,
  Post,
  Query,
  UploadedFile,
  UseGuards,
  UseInterceptors,
  UsePipes,
  ValidationPipe,
} from '@nestjs/common';
import { GroupService } from '../service/group.service';
import { JwtGuard } from '../guards/jwt.guard';
import { FindGroupParamDto } from '../dto/group/find-user.dto';
import { FindGroupPipe } from '../pipes/group/find-group.pipe';
import { DeleteGroupMemberParamDto } from '../dto/group/delete-group-member.dto';
import {
  ApiTags,
  ApiOperation,
  ApiResponse,
  ApiBody,
  ApiConsumes,
} from '@nestjs/swagger';
import { FileObject, FileUploadDto } from '../dto/upload/file.dto';
import { FileInterceptor } from '@nestjs/platform-express';
import { UpdateGroupDto } from '../dto/group/update-group.dto';

@ApiTags('群组')
@Controller('group')
@UseGuards(JwtGuard)
@UsePipes(new ValidationPipe({ transform: true }))
export class GroupController {
  constructor(private groupService: GroupService) {}

  @ApiOperation({ summary: '获取群组列表' })
  @ApiResponse({ status: 200, description: '成功返回群组列表' })
  @Get()
  async getGroups(
    @Query(FindGroupPipe) { pageNum, pageSize }: FindGroupParamDto,
    @Query('keyword') keyword: string,
  ) {
    const data = await this.groupService.getGroups(pageNum, pageSize, keyword);
    return {
      status: 200,
      data,
    };
  }

  @ApiOperation({ summary: '上传群组头像' })
  @ApiResponse({ status: 200, description: '上传成功' })
  @Post('upload')
  @ApiConsumes('multipart/form-data')
  @ApiBody({
    description: '群头像上传',
    type: FileUploadDto,
  })
  @UseInterceptors(FileInterceptor('avatar'))
  async upload(@UploadedFile() file) {
    return {
      status: 200,
      message: '上传成功',
      data: {
        url: `/${(file as FileObject).filename}`,
      },
    };
  }

  @ApiOperation({ summary: '更新群组信息' })
  @ApiResponse({ status: 200, description: '更新成功' })
  @ApiResponse({ status: 404, description: '更新失败' })
  @Patch()
  async updateGroup(@Body() updateGroupDto: UpdateGroupDto) {
    const updateGroup = await this.groupService.updateGroup(updateGroupDto);
    if (updateGroup.acknowledged) {
      return {
        status: 200,
        message: '更新成功',
      };
    } else {
      throw new NotFoundException('更新失败');
    }
  }

  @ApiOperation({ summary: '移除群组成员' })
  @ApiResponse({ status: 200, description: '删除成功' })
  @ApiResponse({ status: 404, description: '删除失败' })
  @Delete('member')
  async removeGroupMember(@Query() deleteMemberDto: DeleteGroupMemberParamDto) {
    const { groupId, userId } = deleteMemberDto;
    const res = await this.groupService.removeGroupMember(groupId, userId);
    if (res.acknowledged) {
      return {
        status: 200,
        message: '删除成功',
      };
    } else {
      throw new NotFoundException('删除失败');
    }
  }
}
